package com.ulook.lookplanet.ui.square.pub;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.lifecycle.ViewModelProvider;

import com.donkingliang.imageselector.utils.ImageSelector;
import com.donkingliang.imageselector.utils.ImageUtil;
import com.donkingliang.imageselector.utils.UriUtils;
import com.qmuiteam.qmui.skin.QMUISkinManager;
import com.qmuiteam.qmui.util.QMUIDisplayHelper;
import com.qmuiteam.qmui.widget.QMUIFloatLayout;
import com.qmuiteam.qmui.widget.QMUIRadiusImageView2;
import com.qmuiteam.qmui.widget.QMUITopBarLayout;
import com.qmuiteam.qmui.widget.dialog.QMUIBottomSheet;
import com.qmuiteam.qmui.widget.popup.QMUIPopup;
import com.qmuiteam.qmui.widget.popup.QMUIPopups;
import com.ulook.lookplanet.R;
import com.ulook.lookplanet.common.ActivityCode;
import com.ulook.lookplanet.data.model.TArtTopic;
import com.ulook.lookplanet.data.model.TArticle;
import com.ulook.lookplanet.data.model.TCommunity;
import com.ulook.lookplanet.data.model.TTopic;
import com.ulook.lookplanet.ui.square.community.CommunityActivity;
import com.ulook.lookplanet.util.StringUtil;
import com.ulook.lookplanet.util.ThrowException;
import com.ulook.lookplanet.widget.AudioPlayerLayout;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.UUID;

/**
 * 发布页面
 */
public class PubActivity extends AppCompatActivity {

    private PubViewModel viewModel;

    private int userId;
    private List<File> images = new ArrayList<>();  // 图片地址列表
    private String audioFileName;     // 录音文件
    private MediaRecorder mMediaRecorder; //录音类
    private Button chooseCom;
    private Button chooseTopic;
    private QMUIFloatLayout topicLayout;
    private EditText contentEditText;
    private QMUIPopup mNormalPopup;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pub);

        userId = getIntent().getIntExtra("userId", 0);
        if(userId == 0){
            Toast.makeText(this, "未登陆账号", Toast.LENGTH_LONG).show();
            finish();
        }
        // 检查权限
        checkPermission();

        viewModel = new ViewModelProvider(this).get(PubViewModel.class);
        viewModel.getToastText().observe(this, s -> {
            Toast.makeText(this, s, Toast.LENGTH_SHORT).show();
        });
        viewModel.getPubState().observe(this, pubState -> {
            if(pubState.getUpLoad() != null){
                findViewById(R.id.pub_progress).setVisibility(View.VISIBLE);
            }
            if(pubState.getComplete() != null){
                finish();
            }if(pubState.getFail() != null){
                findViewById(R.id.pub_progress).setVisibility(View.GONE);
            }
        });


        initPage();
    }

    /**
     * 权限申请
     */
    private void checkPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            String[] permissions = new String[]{Manifest.permission.RECORD_AUDIO,Manifest.permission.WRITE_EXTERNAL_STORAGE};
            for (String permission : permissions) {
                if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(this, permissions, ActivityCode.PERMISSION_CODE);
                    return;
                }
            }
        }
    }
    /**
     * 权限申请结果
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && requestCode == ActivityCode.PERMISSION_CODE) {
            for (int i = 0; i < permissions.length; i++) {
                // 没有权限，主动跳转到权限设置页面
                if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                    Intent intent = new Intent();
                    intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                    Uri uri = Uri.fromParts("package", getPackageName(), null);
                    intent.setData(uri);
                    startActivityForResult(intent, ActivityCode.PERMISSION_CODE);
                    return;
                }
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode){
            // 设置页面获取权限的结果
            case ActivityCode.PERMISSION_CODE :
                if (resultCode == RESULT_OK) {
                    checkPermission();
                }
                break;
            //获取图片选择器返回的数据
            case ActivityCode.LOCAL_IMAGE :
                if(data != null){
                    ArrayList<String> images = data.getStringArrayListExtra(ImageSelector.SELECT_RESULT);
                    displayImages(images);
                }
                break;
        }
    }

    @Override
    public void finish() {
        // 清空本次页面的缓存文件
        if(audioFileName != null){
            File file = new File(getExternalCacheDir() + File.separator + audioFileName);
            if(file.exists() && file.isFile()){
                file.delete();
            }
        }
        if(images != null){
            for(int i = 0; i < images.size(); i++){
                File file = images.get(i);
                if(file.exists() && file.isFile()){
                    file.delete();
                }
            }
        }
        super.finish();
    }

    /**
     * 初始化页面组件
     */
    private void initPage(){
        contentEditText = findViewById(R.id.pub_content);

        QMUITopBarLayout topBar = findViewById(R.id.pub_bar);
        topBar.setTitle(R.string.pub_page_title);
        topBar.addLeftBackImageButton().setOnClickListener(view -> {
            finish();
        });
        // 发布按钮
        topBar.addRightImageButton(R.drawable.ic_pub_article_24dp, 0).setOnClickListener(view -> {
            PubArticleInfo pubArticleInfo = getPageInfo();
            if(pubArticleInfo != null){
                viewModel.pubArticle(pubArticleInfo);
            }
        });
        // 图片按钮
        findViewById(R.id.pub_image_bt).setOnClickListener(view -> {
            showImageBottomPopup();
        });
        // 录音按钮
        findViewById(R.id.pub_audio_bt).setOnClickListener(view -> {
            showAudioButton();
        });
        // 选择分组
        chooseCom = findViewById(R.id.pub_choose_group_bt);
        chooseCom.setOnClickListener(view -> {
            showComPop();
        });
        // 选择话题
        topicLayout = findViewById(R.id.pub_topic_layout);
        chooseTopic = findViewById(R.id.pub_choose_topic_bt);
        chooseTopic.setOnClickListener(view -> {
            showTopicPop();
        });
    }

    /**
     * 获取页面信息，发布帖子
     */
    private PubArticleInfo getPageInfo(){
        PubArticleInfo pubArticleInfo = new PubArticleInfo();

        TArticle article = new TArticle();
        article.setUid(viewModel.getUid());
        article.setAuthor(userId);          // 用户id
        String content = contentEditText.getText().toString();
        if(StringUtil.isEmpty(content)){
            Toast.makeText(this, "内容不能为空", Toast.LENGTH_SHORT).show();
            return null;
        }
        article.setContent(content);        // 文章类容
        article.setHaspic(images.size());   // 图片数量
        if(audioFileName != null){
            article.setAudrofile(audioFileName);
            File audio = new File(getExternalCacheDir().getPath() + File.separator + audioFileName);
            pubArticleInfo.setAudioFile(audio);   // 录音文件
        }
        if(viewModel.getChooseCom() != null){   // 所选分组
            article.setComuid(viewModel.getChooseCom().getUid());
        }else {
            article.setComuid("0");
        }
        article.setHastopic(viewModel.getArtTopics().size()); // 话题数量
        pubArticleInfo.setArticle(article);

        pubArticleInfo.setPicFileList(images);  // 图片文件列表

        //pubArticleInfo.setArtTopicList(viewModel.getArtTopics());  // 话题列表

        return pubArticleInfo;
    }

    /**
     * 选择分组弹窗
     */
    private void showComPop(){
        if(viewModel.getCommunities() == null){
            return;
        }
        List<TCommunity> tCommunities = viewModel.getCommunities();
        String[] listItems = new String[tCommunities.size()];
        for(int i = 0; i < tCommunities.size(); i++){
            listItems[i] = new String(tCommunities.get(i).getName());
        }
        List<String> data = new ArrayList<>();
        Collections.addAll(data, listItems);

        ArrayAdapter adapter = new ArrayAdapter<>(this, R.layout.simple_list_item, data);
        AdapterView.OnItemClickListener onItemClickListener = new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                // 设置选中的Item
                chooseCom.setText(viewModel.getCommunities().get(i).getName());
                viewModel.setChooseCom(viewModel.getCommunities().get(i));
                if (mNormalPopup != null) {
                    mNormalPopup.dismiss();
                }
            }
        };
        mNormalPopup = QMUIPopups.listPopup(this,
                QMUIDisplayHelper.dp2px(this, 250),
                QMUIDisplayHelper.dp2px(this, 300),
                adapter,
                onItemClickListener)
                .animStyle(QMUIPopup.ANIM_GROW_FROM_CENTER)
                .preferredDirection(QMUIPopup.DIRECTION_TOP)
                .shadow(true)
                .offsetYIfTop(QMUIDisplayHelper.dp2px(this, 5))
                .skinManager(QMUISkinManager.defaultInstance(this))
                .onDismiss(new PopupWindow.OnDismissListener() {
                    @Override
                    public void onDismiss() {

                    }
                })
                .show(chooseCom);
    }

    /**
     * 选择话题弹窗
     */
    private void showTopicPop(){
        Log.d("####-choose_topic", "showTopicPop");
        if(viewModel.getTopics() == null){
            return;
        }
        List<TTopic> topics = viewModel.getTopics();
        String[] listItems = new String[topics.size()];
        for(int i = 0; i < topics.size(); i++){
            listItems[i] = new String(topics.get(i).getName());
        }
        List<String> data = new ArrayList<>();
        Collections.addAll(data, listItems);

        ArrayAdapter adapter = new ArrayAdapter<>(this, R.layout.simple_list_item, data);
        AdapterView.OnItemClickListener onItemClickListener = new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                // 设置选中的Item
                TArtTopic tArtTopic = new TArtTopic();
                tArtTopic.setArtid(viewModel.getUid());
                tArtTopic.setTopicid(viewModel.getTopics().get(i).getUid());
                viewModel.addTopic(tArtTopic);
                // 展示
                TextView textView = new TextView(PubActivity.this);
                textView.setText(viewModel.getTopics().get(i).getName());
                textView.setTextColor((PubActivity.this).getResources().getColor(R.color.light_blue_600));
                topicLayout.addView(textView);

                if (mNormalPopup != null) {
                    mNormalPopup.dismiss();
                }
            }
        };
        mNormalPopup = QMUIPopups.listPopup(this,
                QMUIDisplayHelper.dp2px(this, 250),
                QMUIDisplayHelper.dp2px(this, 300),
                adapter,
                onItemClickListener)
                .animStyle(QMUIPopup.ANIM_GROW_FROM_CENTER)
                .preferredDirection(QMUIPopup.DIRECTION_TOP)
                .shadow(true)
                .offsetYIfTop(QMUIDisplayHelper.dp2px(this, 5))
                .skinManager(QMUISkinManager.defaultInstance(this))
                .onDismiss(new PopupWindow.OnDismissListener() {
                    @Override
                    public void onDismiss() {
                    }
                })
                .show(chooseTopic);
    }

    /**
     * 展示选中的图片
     */
    private void displayImages(List<String> imageList){
        // 将图片转换成临时缓存并重命名
        for(int i = 0; i < imageList.size(); i++){
            Uri uri = UriUtils.getImageContentUri(PubActivity.this, imageList.get(i));
            Bitmap bitmap = ImageUtil.getBitmapFromUri(PubActivity.this, uri);
            String imageName = UUID.randomUUID() + ".jpg";
            // 创建缓存文件
            File imageFile = new File(getExternalCacheDir().getPath() + File.separator + imageName);
            try {
                // 写入文件
                BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(imageFile));
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
                bos.flush();
                bos.close();
            } catch (IOException e) {
                ThrowException.print(e, "图片转化失败");
                return;
            }
            images.add(imageFile);
        }

        QMUIFloatLayout imageLayout = findViewById(R.id.pub_image_layout);
        int size = images.size();
        int width = imageLayout.getWidth();
        int imageWidth;
        if(size == 1){
            imageWidth = width;
        }else if (size == 2 || size == 4){
            imageWidth = (width - 2) / 2;
        }else {
            imageWidth = (width -3) / 3;
        }
        imageLayout.removeAllViews();
        for(int i = 0; i < size; i++){
            ImageView imageView = new ImageView(this);
            imageView.setImageURI(UriUtils.getImageContentUri(this, images.get(i).getPath()));
            GridLayout.LayoutParams layoutParams = new GridLayout.LayoutParams();
            layoutParams.width = imageWidth;
            layoutParams.height = imageWidth;
            imageView.setLayoutParams(layoutParams);
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            imageLayout.addView(imageView, i);
        }
    }

    /**
     * 底部弹窗：选择图片方式
     */
    private void showImageBottomPopup(){
        QMUIBottomSheet.BottomListSheetBuilder builder = new QMUIBottomSheet.BottomListSheetBuilder(this);
        builder.setGravityCenter(true)
                .addItem("相册图片")
                .addItem("相机拍照")
                .setOnSheetItemClickListener((dialog, itemView, position, tag) -> {
                    switch (tag){
                        case "相册图片":
                            ArrayList<String> images = new ArrayList<>();
                            ImageSelector.builder()
                                    .useCamera(false) // 设置是否使用拍照
                                    .setSingle(false)  //设置是否单选
                                    .setMaxSelectCount(9) // 图片的最大选择数量，小于等于0时，不限数量。
                                    .setSelected(images) // 把已选的图片传入默认选中。
                                    .canPreview(true) //是否可以预览图片，默认为true
                                    .start(PubActivity.this, ActivityCode.LOCAL_IMAGE); // 打开相册
                            break;
                        case "相机拍照":
                            break;
                    }
                    dialog.dismiss();
                }).build().show();
    }

    /**
     * 录音
     */
    private void showAudioButton(){
        LinearLayout audioLayout = findViewById(R.id.pub_audio_bt_layout);
        audioLayout.setVisibility(View.VISIBLE);
        audioLayout.setOnClickListener(view -> {
            audioLayout.setVisibility(View.GONE);
        });
        QMUIRadiusImageView2 imageView = findViewById(R.id.pub_audio_bt_big);
        imageView.setOnTouchListener((view, motionEvent) -> {
            if(motionEvent.getAction() == MotionEvent.ACTION_DOWN){
                startRecord();
            }
            if(motionEvent.getAction() == MotionEvent.ACTION_UP){
                stopRecord();
                audioLayout.setVisibility(View.GONE);
                showAudioPlayer();
            }
            return false;
        });
    }
    /**
     * 开始录音
     */
    private void startRecord(){
        //ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.RECORD_AUDIO}, 1);
        /* ①Initial：实例化MediaRecorder对象 */
        if (mMediaRecorder == null)
            mMediaRecorder = new MediaRecorder();
        try {
            /* ②setAudioSource/setVedioSource */
            mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);// 设置麦克风

            /*
             * ②设置输出文件的格式：THREE_GPP/MPEG-4/RAW_AMR/Default THREE_GPP(3gp格式
             * ，H263视频/ARM音频编码)、MPEG-4、RAW_AMR(只支持音频且音频编码要求为AMR_NB)
             */
            mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
            /* ②设置音频文件的编码：AAC/AMR_NB/AMR_MB/Default 声音的（波形）的采样 */
            mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
            // 设置文件名
            audioFileName = UUID.randomUUID() + ".m4a";
            /* ③准备 */
            mMediaRecorder.setOutputFile(getExternalCacheDir().getPath() + File.separator + audioFileName);
            mMediaRecorder.prepare();
            /* ④开始 */
            mMediaRecorder.start();
            mMediaRecorder.setOnErrorListener((mediaRecorder, var1, var2) -> {
                Toast.makeText(this, "录音失败", Toast.LENGTH_SHORT).show();
            });
        } catch (IOException e) {
            ThrowException.print(e, "录音失败");
        }
    }
    /**
     * 结束录音
     */
    private void stopRecord(){
        try {
            mMediaRecorder.stop();
            mMediaRecorder.release();
            mMediaRecorder = null;
        } catch (RuntimeException e) {
            mMediaRecorder.reset();
            mMediaRecorder.release();
            mMediaRecorder = null;
        }
    }

    /**
     * 显示播放控件
     */
    private void showAudioPlayer(){
        AudioPlayerLayout audioPlayerLayout = findViewById(R.id.audio_player_layout);
        audioPlayerLayout.setVisibility(View.VISIBLE);
        audioPlayerLayout.setMediaPath(getExternalCacheDir() + File.separator + audioFileName);
    }

}